<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
  <base href="/">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="apple-mobile-web-app-capable" content="no">
  <meta name="format-detection" content="telephone=no">
  <title>注册</title>
  <script src="static/js/cssrem.js"></script>
<link href="static/css/style.css" rel="stylesheet"></head>
<body>
  <div class="content mark-content-top">
    <div class="wrapper"><a class="btn-home dib" href="${domain}/index"></a>
      <div class="icon-reg auto"></div>
      <div class="registered cells bgwh">
        <div class="cell">
          <div class="cell-hd">手机号</div>
          <div class="cell-bd"><input class="ui-res-input" id="phone" name="phone" type="tel" placeholder="请输入手机号" data-verified="^1[3-9]\d{9}$"
              data-tips="手机号不能为空！|请输入正确的手机号！" maxlength="11"></div>
        </div>
        <div class="cell">
          <div class="cell-hd">验证码</div>
          <div class="cell-bd">
            <div class="cell">
              <div class="cell-bd"><input class="ui-res-input" type="tel" name="phone" placeholder="请输入验证码" maxlength="6" data-verified="^\d{6}$"
                  data-tips="请输入验证码！|请输入6位数字的验证码！"></div>
              <div class="cell-fd"><a class="f24 white verified disabled" href="javascript:;">发送验证码</a></div>
            </div>
          </div>
        </div>
        <div class="cell">
          <div class="cell-hd">密码</div>
          <div class="cell-bd"><input class="ui-res-input" type="password" name="password" placeholder="6-18位字母数字组合"  maxlength="18" data-verified="^[\d\w]{6,18}$"
              data-tips="密码不能为空！|请输入6-18位由数字或字母组成的密码！"></div>
        </div>
        <div class="cell">
          <div class="cell-hd">邀请人</div>
          <div class="cell-bd"><input class="ui-res-input inviteCode" type="tel" name="phone" placeholder="请输入邀请码（选填）" data-required data-verified="^1[3-9]\d{9}$"
              data-tips="手机号不能为空！|请输入正确的手机号！" maxlength="11"></div>
        </div>
      </div>
      <div class="mt10 cell">
        <span class="cell-hd f0 pl0 ml20">
          <a class="icon-checked ml20 f0" href="javascript:;"></a>
        </span>
        <span class="cell-bd f24 g9">我已阅读并同意<a class="g-primary" href="${domain}/protocol">《万果用户注册协议》</a></span>
      </div>
      <div class="m20 p20"></div>
      <p class="m20 pl20 pr20"><a id="register" class="ui-login-btn ui-login-btn--primary ui-login-btn--medium db f32 ui-login-btn--disabled js-btn-submit"  href="javascript:;">注册</a></p>
    </div>
  </div>
<input class="openid" type="hidden" value="${openid}">
<input class="forward" type="hidden" value="${forward}">
<input class="regType" type="hidden" value="${regType}">
<script src="//cdn.bootcss.com/babel-polyfill/6.23.0/polyfill.min.js"></script>
<script src="static/js/layer_mobile/layer.js"></script>
<script type="text/javascript" src="static/js/app.js"></script>
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.16.2/axios.min.js"></script>
<script src="//res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>	
<script src="static/js/wx-share.js"></script>
<script>
  var wxShare  = new WxShare({
	  title: '注册万果田园', 
	  des: '注册万果田园，完成农作物认养。绿色美味的水果蔬菜送到家！', 
	  linkUrl: location.href, 
	  imgUrl: 'http://fruit-picture.oss-cn-beijing.aliyuncs.com/fruit/share/shareimg.png'
  })
  
  if(wxShare.hasCookie('inviteCode')){
	  var inviteCode = wxShare.getCookie('inviteCode')
	  var ele = document.querySelector('.inviteCode')
	  ele.value = inviteCode
  }
  	//注册
    function submitReg(){
	   	var parent  = document.querySelector('.registered')
	   	var inputs = parent.querySelectorAll('input')
	   	var phone = inputs[0].value
	   	var smsCode= inputs[1].value
	   	var pwd = inputs[2].value
	   	var parentName= inputs[3].value
	   	var formData = new FormData()
        formData.append('phone',phone)
        formData.append('smsCode',smsCode)
        formData.append('pwd',md5(pwd))
        formData.append('parentName',parentName)
        formData.append('type',"register")
        var openid = document.querySelector(".openid").value
        var regType = document.querySelector(".regType").value
        if(regType == '1'){
      	 	formData.append('openid',openid)
      	 	submit('wap/login/registerForWeChat',formData)
        } else {
        	submit('wap/login/register',formData)
        }
    }
    var isSubmitDisabled = false
    var btnSubmit = document.querySelector('.js-btn-submit')
    var btn =document.querySelector('.icon-checked')
    btn.addEventListener('click',function(){
      if(this.classList.contains('active')){
        this.classList.remove('active')
      }else{
        this.classList.add('active')
      }
    });
    
    
    (function(){
      var elements = document.querySelectorAll('[data-verified]')
      var submits = document.querySelector('#register')
      var eChecked =document.querySelector('.icon-checked')
      var eEerified = document.querySelector('.verified')
      var isSubmit = true
      for (var i = 0; i < elements.length; i++) {
        var element = elements[i]
        element.addEventListener('input', function () {
            var value = this.value.trim()
            if (this.name === 'phone') {
              this.value = value.replace(/\D+/, '')
              if (this.id === 'phone') {
                if (/^1[3-9]\d{9}/.test(this.value)) {
                  eEerified.classList.remove('disabled')
                } else {
                  eEerified.classList.add('disabled')
                }
              }
            } else if (this.name === 'password') {
              this.value = value.match(/[\w\d]+/g)
            }
            submitActive()
          })
        element.addEventListener('blur', function() {
          verified(this)
        })
      }
      //for (var i = 0; i < submits.length; i++) {
        var btn = submits
        btn.addEventListener('click', function(e) {
          //isSubmit = false
          e.preventDefault()
          var isDisabled = this.classList.contains('ui-login-btn--disabled')
          var status
          if (isDisabled) return false
          for (var i = 0; i < elements.length; i++) {
            var element = elements[i]
            status = verified(element)
            if (elements.length - 1 === i && status) {
              if(!eChecked.classList.contains('active')){
                return showTips('请阅读并同意《万果用户注册协议》')
              }
              submitReg()
            } else if (status === 1) {
              continue;
            } else if (!status) {
              break;
            }
          }
        })
      //}
    }());

  
  
  function verified(self) {
      var tips = self.dataset.tips.indexOf('|') > -1 ? self.dataset.tips.split('|') : self.dataset.tips
      var pattern = self.dataset.verified
      var value = self.value
      var required = self.dataset.required !== ''
      // 不是必须验证
      if (!required) return 1
      if (pattern !== 'true' || pattern !== 'false') {
        var value = self.value
        if (value.trim() === '') {
          showTips(tips[0])
          return false
        } else if (!setRegExp(pattern, value) && (!pattern || pattern !== 'false')) {
          showTips(tips[1])
        }
      }
      return setRegExp(pattern, value)
    }

  function setRegExp(pattern, value) {
    var re = new RegExp(pattern, 'g')
    return re.test(value)
  }
  function showTips(tips) {
    layer.open({
      content: tips,
      skin: 'msg',
      time: 2
    })
  }
    
    
    
    function submit(url,params){
    	
    	axios({
            method: 'post',
            url: url,
            data:params,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (res) {
        	var state = res.data.result.state
        	var message = res.data.result.message
        	if(state!=1){
        		return layer.open({ content: message,skin:'msg',time: 2 })
        	}
       		var d = document.querySelector(".forward").value
       		if(d != ''){location.href=d}
        }).catch(function(err){
        	console.log(err)
        	layer.open({ content: '请求失败！',skin:'msg',time: 2 }) 
        })
    }
    
    // 发验证码
    (function verifiedCode(){
      var btn = document.querySelector('.verified')
      var seconds,time

      btn.addEventListener('click',function(){
    	var _this = this 
        /* var phone = document.querySelector('#phone')
        var phoneValue = phone.value.trim()
        var re = /^1[2-9]\d{9}$/g
        var tips = phoneValue===''?'手机号不能为空！':'输入手机号格式错误'
        if(!re.test(phoneValue)){
          return layer.open({
            content: tips,
            skin: 'msg',
            time: 2
          })
        } */
        if(this.classList.contains('disabled')) return false;
        this.classList.add('disabled')
        var formData = new FormData()
        formData.append('phone',phone.value)
        formData.append('type','register')
        axios({
            method: 'post',
            url: 'wap/sms/send',
            data:formData,
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (res) {
        	var state = res.data.result.state
        	var message = res.data.result.message
        	layer.open({ content: message,skin:'msg',time: 2 })
        	
        	if(state==1){
        		countdown()
        	}else{
        		_this.classList.remove('disabled')
        	}
        }).catch(function(){})
        
      });
      init()

      function init(){
        seconds = 60
        clearTimeout(time)
        btn.textContent = '发送验证码'
      }

      function countdown(){
        if(seconds<=0) return init(), btn.classList.remove('disabled');
        seconds-=1
        btn.textContent =seconds+'秒后重新获取'
        time = setTimeout(countdown,1000)
      }


    }());
    function submitActive() {
        var eInputs = document.querySelectorAll('[data-verified]')
        var btnSubmit = document.querySelector('.js-btn-submit')
        var eChecked = document.querySelector('.icon-checked')
        for (var i = 0; i < eInputs.length; i++) {
          var element = eInputs[i];
          var value = element.value.trim()
          var regexp = new RegExp(element.dataset.verified, 'g')
          var d = regexp.test(value)
          var required = element.dataset.required !== ''
          if (!required) {
            continue;
          }
          if (!d) {
            isSubmitDisabled = false
            btnSubmit.classList.add('ui-login-btn--disabled')
            break;
          } else {
            isSubmitDisabled = true
            btnSubmit.classList.remove('ui-login-btn--disabled')
          }
        }
        return isSubmitDisabled
      }



  </script>
	<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?24fb3d27099c50ae04b59301e492b50c";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
</body>
</html>
